import React, { useState, useEffect, useCallback, useRef } from 'react';
import Search from 'antd/lib/input/Search';
import { Space, Button, Table, message, Switch, Modal, Dropdown, Menu } from 'antd';
import './style.scss';
import { ColumnsType } from 'antd/lib/table';
import { QuestionAnswerInfo } from 'admin/schema/QuestionAnswer';
import {
  getQuestionAnswers,
  switchQuestionAnswer,
  deleteQa,
  getQAUploadInfo,
  confirmUploadQuestion,
  getBatchStudyProgressByVersion,
  confirmStudyIntention,
  batchUnderstandByVersion,
} from 'admin/servers/servers';
import UploadBatchModal from '../UploadBatchModal';
import { commonAiDownload } from '../IntentionLibrary';
import { useHistory } from 'react-router-dom';
import { deleteRowChangePageNum } from 'utils/tools';
import UploadingPic from '../UploadingPic';
import { debounce } from 'lodash';

import { JSONObject } from 'admin/schema/common';
import produce from 'immer';
import { useDispatch, useSelector } from 'react-redux';
import { questionAction } from 'store/question';

/**
 * 问答库
 * AI管理-机器人管理-版本管理-配置话术流程-问答库
 */
const QALibrary: React.FC<{ versionId: number }> = ({ versionId }) => {
  const history = useHistory();
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // table列表数据
  const [qaList, setQaList] = useState<QuestionAnswerInfo[]>([]);
  const [switchLoadings, setSwitchLoadings] = useState<number[]>([]);
  // 上传弹窗
  const [uploadVisble, setUploadVisble] = useState(false);
  // 导入问答-进度值
  const [progressData, setProgressData] = useState<{
    status: number;
    percent: number;
    errorReason: string;
    type?: string;
  }>();
  // 批量学习意图-进度值
  const [studyProgressData, setStudyProgressData] = useState<{
    status: number;
    percent: number;
    errorReason: string;
    type?: string;
  }>();
  // 页面卸载标志：true-卸载
  const isUnmount = useRef<any>(undefined);
  // 计时器-刷新列表，显示导入进度计时器
  const timer = useRef<any>(undefined);

  /**存储搜索条件 */
  const searchForm = useSelector((state: JSONObject) => state.questionList.searchForm);
  const dispatch = useDispatch();

  /**
   * 查询上传进度
   */
  const checkUploading = useCallback(async () => {
    try {
      const { data } = await getQAUploadInfo(versionId);
      if (isUnmount.current) {
        console.log('>>>>>>>>>>>页面已经卸载-return >>>>>>>>>>>');
        return;
      }
      console.log('查询进度', data);
      const { importStatus, progressFinishedNumber, progressTotalNumber, errorReason } = data;
      if (!importStatus) {
        // 显示列表页面
        clearTimer();
        setProgressData(undefined);
      } else {
        // 显示插画页面
        if (importStatus === 1 || importStatus === 2) {
          // 进行中
          startTimer('upload');
        } else {
          // 完成或者失败，显示【确认】按钮
          clearTimer();
        }
        let percent = 0;
        percent = Math.floor(
          (progressFinishedNumber && progressTotalNumber
            ? progressFinishedNumber / progressTotalNumber
            : 0) * 100
        );
        const newData = { status: importStatus, percent: percent, errorReason: errorReason || '' };
        setProgressData(newData);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      // 出现异常，显示列表页面
      setProgressData({ status: 0, percent: 0, errorReason: '' });
      clearTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [versionId]);
  /**
   * 查询学习进度
   */
  const checkBatchStudying = useCallback(async () => {
    try {
      const { data } = await getBatchStudyProgressByVersion(versionId, 'question');
      if (isUnmount.current) {
        console.log('>>>>>>>>>>>页面已经卸载-return >>>>>>>>>>>');
        return;
      }
      console.log('查询进度', data);
      if (!data) {
        // 显示列表页面
        clearTimer();
        setStudyProgressData(undefined);
      } else {
        // 显示插画页面
        const { isFinish, finishedNumber, totalNumber } = data;
        let studyStatus: number; // 记录状态
        if (!isFinish) {
          // 进行中
          startTimer('study');
          studyStatus = 2;
        } else {
          // 完成显示【确认】按钮
          clearTimer();
          studyStatus = 4;
        }
        // 进度值
        const percent = Math.floor(
          (finishedNumber && totalNumber ? finishedNumber / totalNumber : 0) * 100
        );
        const newData = { status: studyStatus, percent: percent, errorReason: '', type: 'study' };
        setStudyProgressData(newData);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
      // 出现异常，显示列表页面
      setStudyProgressData({ status: 0, percent: 0, errorReason: '', type: 'study' });
      clearTimer();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [versionId]);
  /**
   * 查询table数据
   */
  const getTableData = useCallback(async () => {
    if (progressData || studyProgressData) {
      return;
    }
    setTableLoading(true);
    const { pageNo, pageSize, searchText } = searchForm;
    console.log(searchForm, '查询条件===请求列表接口数据');
    try {
      const { data, count } = await getQuestionAnswers({
        pageNo,
        pageSize,
        versionId,
        questionDescribe: searchText,
      });
      console.log('getTableData -> res', data, count);
      setQaList(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [progressData, searchForm, studyProgressData, versionId]);

  // 进页面查询是否导入问答中
  useEffect(() => {
    isUnmount.current = false;
    checkUploading();
    return () => {
      console.log('leave out！！！-----退出>>>>>问答页面');
      clearTimer();
      // 卸载中
      isUnmount.current = true;
    };
  }, [checkUploading]);

  // 进页面查询是否导入意图中
  useEffect(() => {
    isUnmount.current = false;
    checkBatchStudying();

    return () => {
      console.log('leave out！！！-----退出>>>>>意图页面');
      clearTimer();
      // 卸载中
      isUnmount.current = true;
    };
  }, [checkBatchStudying]);

  useEffect(() => {
    getTableData();
  }, [getTableData]);

  /**
   * 确定操作（导入100%、导入失败）
   * @param versionId
   */
  const handleConfirmUpload = async () => {
    try {
      await confirmUploadQuestion(versionId);
      checkUploading();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 确定操作（学习100%、导入失败）
   * @param versionId
   */
  const handleConfirmStudy = async () => {
    try {
      await confirmStudyIntention(versionId, 'question');
      checkBatchStudying();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**开启定时器 */
  function startTimer(type: 'upload' | 'study') {
    if (timer.current) {
      return;
    }
    // 条件：没有定时器，则开启
    // 开启-定时1s刷新-更新进度条
    timer.current = setInterval(() => {
      console.log('1s****定时刷新-进度条');
      console.log('1s****定时刷新-进度条');
      type === 'upload' && checkUploading();
      type === 'study' && checkBatchStudying();
    }, 1000);
    console.log('启动定时器', type, timer.current);
  }

  /**清除定时器 */
  function clearTimer() {
    if (!timer.current) {
      return;
    }
    clearInterval(timer.current);
    timer.current = null;
  }

  /**上传成功-用户点击确定*/
  function confirmUpload() {
    handleConfirmUpload();
  }

  /**上传失败-用户点击确定*/
  function cancelUpload() {
    handleConfirmUpload();
  }

  /**学习成功-用户点击确定*/
  function confirmStudy() {
    handleConfirmStudy();
  }

  /**学习失败-用户点击确定*/
  function cancelStudy() {
    handleConfirmStudy();
  }

  /**
   * 翻页、每页条数显示变更
   * @param pageNo 点击页码
   * @param pageSize 点击每页条数
   */
  const onChangePage = (pageNo: number, pageSize?: number) => {
    console.log('搜索条件变更***页码+条数', pageNo, pageSize);
    const data: any = produce(searchForm, (draft: any) => {
      draft.pageNo = pageNo;
      if (pageSize) {
        draft.pageSize = pageSize;
      }
    });
    dispatch(questionAction.setSearchForm(data));
  };

  /**
   * 搜索条件变更
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    console.log('搜索条件变更***', text);
    const data: any = produce(searchForm, (draft: any) => {
      draft.searchText = text.trim();
      draft.pageNo = 1;
    });
    dispatch(questionAction.setSearchForm(data));
  };

  /**
   * 点击switch
   */
  const handleSwitchClick = async (checked: boolean, record: QuestionAnswerInfo) => {
    console.log('checked', checked);
    console.log('record', record);
    setSwitchLoadings(prev => {
      return [...prev, record.questionId];
    });
    try {
      await switchQuestionAnswer({
        questionSwitch: checked ? 'on' : 'off',
        questionId: record.questionId,
      });
      qaList.forEach(item => {
        item.questionId === record.questionId && (item.intentionSwitch = checked ? 'on' : 'off');
      });
      setQaList(qaList);
      message.success(`${checked ? '问答已启用' : '问答已停用'}`);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSwitchLoadings(
      switchLoadings.filter(item => {
        return item !== record.questionId;
      })
    );
  };

  /**
   * 对列表数据进行刷新：新增，编辑
   * @param pageNum 最新页码
   */
  const refreshTable = async (newPageNum?: number) => {
    if (newPageNum && newPageNum !== searchForm.pageNo) {
      // 刷新到最新页码
      onChangePage(newPageNum);
    } else {
      // 刷新当前页面
      getTableData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, searchForm.pageNo, searchForm.pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 删除
   */
  const handleDelete = (record: QuestionAnswerInfo) => {
    Modal.confirm({
      title: '删除问答提示',
      content: '删除后无法恢复! 确认删除吗?',
      async onOk() {
        try {
          await deleteQa({
            questionId: record.questionId,
          });
          message.success(`删除成功`);
          deleteFresh(1);
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      },
    });
  };
  /**
   * 点击批量学习按钮
   */
  const handleBatchStudy = async () => {
    try {
      await batchUnderstandByVersion(versionId, 'question');
      checkBatchStudying();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };
  /**
   * Table列描述数据对象
   */
  const columns: ColumnsType<QuestionAnswerInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 80,
      render: (text, record, index) => index + 1 + searchForm.pageSize * (searchForm.pageNo - 1),
    },
    {
      title: '问题',
      dataIndex: 'questionDescribe',
      key: 'questionDescribe',
      ellipsis: true,
    },
    {
      title: '答案',
      dataIndex: 'answer',
      key: 'answer',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'intentionSwitch',
      key: 'intentionSwitch',
      render: (text, record, index) => (
        <Switch
          checked={text === 'on'}
          loading={switchLoadings.includes(record.questionId)}
          onClick={checked => handleSwitchClick(checked, record)}
        />
      ),
    },
    {
      title: '扩展问数量',
      dataIndex: 'extendQuestionTotal',
      key: 'extendQuestionTotal',
    },
    {
      title: '未学习/学习失败扩展问数量',
      dataIndex: 'unStudyNumber',
      key: 'unStudyNumber',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              history.push(
                `/webapp/outbound/ai/robots/version/flow/operateQa?versionId=${versionId}&questionId=${record.questionId}`
              );
            }}
          >
            编辑
          </Button>
          <Button type="link" onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      {/* 1.正常状态：显示列表 */}
      {!progressData && !studyProgressData && (
        <>
          <div className="qalibrary-top" style={{ marginTop: 20 }}>
            <Search
              placeholder="请输入问题"
              enterButton="搜索"
              defaultValue={searchForm?.searchText}
              style={{ width: 300 }}
              onSearch={value => handleSearch(value.trim())}
              allowClear
            />
            <Space>
              <Dropdown.Button
                type="primary"
                onClick={() => {
                  history.push(
                    `/webapp/outbound/ai/robots/version/flow/operateQa?versionId=${versionId}`
                  );
                }}
                overlay={
                  <Menu
                    onClick={({ key }: any) => {
                      if (key === '1') {
                        setUploadVisble(true);
                      } else {
                        commonAiDownload('question', versionId);
                      }
                    }}
                  >
                    <Menu.Item key="1">导入问答</Menu.Item>
                    <Menu.Item key="2">导出问答</Menu.Item>
                  </Menu>
                }
              >
                新建问答
              </Dropdown.Button>
              <Button type="primary" onClick={debounce(handleBatchStudy, 500)}>
                批量学习
              </Button>
            </Space>
          </div>
          <div style={{ marginTop: 20 }} className="mgr-table">
            <Table
              loading={tableLoading}
              columns={columns}
              dataSource={qaList}
              rowKey="questionId"
              pagination={{
                total: total,
                showTotal: (total: number) => `共 ${total} 条`,
                current: searchForm.pageNo,
                pageSize: searchForm.pageSize,
                showSizeChanger: true,
                onChange: onChangePage,
              }}
            />
          </div>
        </>
      )}
      {/* 2.导入状态 */}
      {progressData && (
        <UploadingPic
          progressData={progressData as any}
          callBackFail={cancelUpload}
          callBackSuccess={confirmUpload}
        />
      )}
      {/* 3.批量学习状态 */}
      {studyProgressData && (
        <UploadingPic
          progressData={studyProgressData as any}
          callBackFail={cancelStudy}
          callBackSuccess={confirmStudy}
        />
      )}
      <UploadBatchModal
        show={uploadVisble}
        data={{ versionId: versionId, mode: 'question' }}
        callback={data => {
          setUploadVisble(false);
          if (data) {
            //  导入问答-接口成功
            checkUploading();
          }
        }}
      />
    </>
  );
};

export default QALibrary;
